package com.hopu.blb_erp.controller;

import com.hopu.blb_erp.entity.TOrder;
import com.hopu.blb_erp.service.TOrderService;
import com.hopu.blb_erp.service.UserService;
import com.hopu.blb_erp.utils.RandomNumber;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;

@Api
@RestController

public class TOrderController {
    @Autowired
    private TOrderService tOrderService;
    @Autowired
    private UserService userService;

    @ApiOperation("插入订单")
    @PostMapping("/TOrder")
    public ResponseEntity<String> addTOrder(@RequestBody TOrder tOrder){
        //得到当前用户
        User userDetail = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //通过用户名查询id
        com.hopu.blb_erp.entity.User user = userService.findByName(userDetail.getUsername());
        Integer id = user.getId();
        //获得随机字符作为订单编号
        String tOrderId = RandomNumber.getItemID(20);
        tOrder.setOrderId(tOrderId);
        //获取当前时间为交易时间
        long l = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(l);
        tOrder.setDealTime(timestamp);
        //设置交付
        tOrder.setProductId(tOrder.getProductId());
        tOrder.setCustomId(id);
        tOrder.setNumber(tOrder.getNumber());
        double money = tOrder.getMoney();
        tOrder.setMoney(Double.parseDouble((money * tOrder.getNumber())+""));
        tOrder.setOrderStatus("已支付");
        tOrder.setPayType("支付宝");
        tOrderService.save(tOrder);
        return ResponseEntity.ok("ok");
    }
}
